using Xfoil, Printf
using CCBlade
using Distributed

@everywhere function clcdtable(filename; re = 1e6, mach = 0.0, cr75 = 0.37)

    # read airfoil into XFOIL
    open(filename, "r") do f
        x = Float64[]
        y = Float64[]
        for line in eachline(f)
            entries = split(chomp(line))
            push!(x, parse(Float64, entries[1]))
            push!(y, parse(Float64, entries[2]))
        end
        Xfoil.set_coordinates(x,y)
    end

    # repanel using XFOIL's `PANE` command
    Xfoil.pane()

    # set operating conditions
    alpha = -13:1:20
    re = re
    mach = mach

    # initialize outputs
    n_a = length(alpha)
    c_l = zeros(n_a)
    c_d = zeros(n_a)
    c_dp = zeros(n_a)
    c_m = zeros(n_a)
    converged = zeros(Bool, n_a)
    for i = 1:n_a
        c_l[i], c_d[i], c_dp[i], c_m[i], converged[i] = Xfoil.solve_alpha(alpha[i], re; mach, iter=100)
    end

    # print results
    println("Angle\t\tCl\t\tCd\t\tCm\t\tConverged")
    for i = 1:n_a
    @printf("%8f\t%8f\t%8f\t%8f\t%d\n",alpha[i],c_l[i],c_d[i],c_m[i],converged[i])
    end

    # exitrapolation 
    alpha_0 = alpha/180.0*pi 
    cl_0 = c_l 
    cd_0 = c_d 
    cr75 = cr75
    alpha_ext, cl_ext, cd_ext = viterna(alpha_0, cl_0, cd_0, cr75)

    return alpha_ext, cl_ext, cd_ext 
end 

a_dbln526, cl_dbln526, cd_dbln526 = clcdtable("dbln526.dat"; mach = 100.0/345.0)
nothing 

a_0, cl_0, cd_0 = clcdtable("dbln526.dat"; mach = 0.0)
nothing 

a_naca4412, cl_naca4412, cd_naca4412 = clcdtable("naca2412.dat"; mach = 100.0/345.0)
nothing